package com.ebeitech.auction.view.homepage.mvppresenter;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.ebeitech.auction.R;
import com.ebeitech.auction.application.EbeiApplication;
import com.ebeitech.auction.db.CommonDBHelper;
import com.ebeitech.auction.domain.User;
import com.ebeitech.auction.domain.dao.UserDao;
import com.ebeitech.auction.http.EbeiErrorCode;
import com.ebeitech.auction.http.HttpService;
import com.ebeitech.auction.http.model.LoginModel;
import com.ebeitech.auction.http.service.HttpCommonServiceRx;
import com.ebeitech.auction.view.homepage.mvpview.LoginContract;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.land.auction.wxapi.WeiXinUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by alice on 2017/10/25.
 */
public class LoginPresenter implements LoginContract.Presenter {

	private LoginContract.View mView;

	public LoginPresenter(LoginContract.View view) {
		this.mView = view;
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case 0: {
					Context context = (Context) msg.obj;
					final String userAccount = SPManager.getInstance().get(SPConstants.USER_ACCOUNT, "");
					final String userPassword = SPManager.getInstance().get(SPConstants.USER_PASSWORD, "");
					if (StringUtil.isEmpty(userAccount)) {
						mView.showLoginFrame();
						return;
					} else {
						mView.showUserAccount(userAccount, userPassword);
						doAutoLogin(context, userAccount, userPassword);
					}
				}
				break;
				default:
					break;
			}

		}
	};

	@Override
	public void autoLogin(Context context) {
		Message message = new Message();
		message.what = 0;
		message.obj = context;
		mHandler.sendMessageDelayed(message, 500);
	}

	public void doAutoLogin(final Context context, String userAccount, final String userPassword) {
		new AsyncTask<String, Void, Void>() {
			User user;

			@Override
			protected Void doInBackground(String... params) {
				String userAccount = params[0];
				CommonDBHelper.changeDBHelper(userAccount);
				user = UserDao.getInstance().getLoginUser(userAccount, userPassword);
				return null;
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				super.onPostExecute(aVoid);
				if (user != null && !StringUtil.isEmpty(user.getUserAccount())) {
					EbeiApplication.setUser(user);
					mView.setIsHomeShowVersionUpdateDialog(true);
					mView.loginSuccess();
				} else {
					mView.showLoginFrame();
				}

			}
		}.execute(userAccount);
	}

	/**
	 * 联网登陆
	 * @param userAccount
	 * @param password
	 */
	@Override
	public void doLogin(final String userAccount, final String password) {
		final Context context = EbeiApplication.getContext();
		HttpCommonServiceRx CommonServiceRx = HttpService.getInstance().getRxGsonRetrofit().create(HttpCommonServiceRx.class);
		Map<String, String> params = new HashMap<String, String>();
		params.put("userAccount", userAccount);
		params.put("password", password);
		Call<ResponseBody> call = CommonServiceRx.doLogin(params);
		HttpService.getInstance().executeHttp(context, call, new HttpService.HttpListener<LoginModel>() {
			@Override
			public void onStart() {
				mView.showProgress(context.getString(R.string.ebei_login_doing));
			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				String errorMsg = errorCode.getErrorMsg();
				if (StringUtil.isEmpty(errorMsg)) {
					errorMsg = context.getString(R.string.ebei_login_failure);
				}
				mView.showLoginResult(errorMsg);
				mView.dismissProgress();
				mView.showLoginFrame();
			}

			@Override
			public void onSuccess(LoginModel loginModel) {
				if (loginModel == null) {
					mView.showLoginResult(context.getString(R.string.ebei_login_failure));
					return;
				}

				if ("1".equals(loginModel.getResultCode())
						&& loginModel.getData() != null && loginModel.getData().getUserVO() != null) {
					loginSuccess(loginModel);
				} else {
					mView.showLoginFrame();
				}
				mView.dismissProgress();
			}
		}, LoginModel.class, false);
	}

	@Override
	public void loginSuccess(LoginModel loginModel) {
		User user = loginModel.getData().getUserVO();
		user.setLoginStatus("1");
		EbeiApplication.setUser(user);
		UserDao.getInstance().insertOrUpdate(user);
		mView.loginSuccess();
	}

	@Override
	public void doWeiXinLogin(String userAccount, String password) {
		WeiXinUtil.getInstance().doLogin();
	}

	@Override
	public void doBindWeiXin(String accessToken, String userAccount, String password) {
		final Context context = EbeiApplication.getContext();
		HttpCommonServiceRx CommonServiceRx = HttpService.getInstance().getRxGsonRetrofit().create(HttpCommonServiceRx.class);
		Map<String, String> params = new HashMap<String, String>();
		params.put("accessToken", accessToken);
		params.put("userAccount", userAccount);
		params.put("password", password);
		Call<ResponseBody> call = CommonServiceRx.doBindWeiXin(params);
		HttpService.getInstance().executeHttp(context, call, new HttpService.HttpListener<LoginModel>() {
			@Override
			public void onStart() {
				mView.showProgress(context.getString(R.string.ebei_bind_doing));
			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				String errorMsg = errorCode.getErrorMsg();
				if (StringUtil.isEmpty(errorMsg)) {
					errorMsg = context.getString(R.string.ebei_login_failure);
				}
				mView.showLoginResult(errorMsg);
				mView.dismissProgress();
				mView.showLoginFrame();
			}

			@Override
			public void onSuccess(LoginModel loginModel) {
				if (loginModel == null) {
					mView.showLoginResult(context.getString(R.string.ebei_login_failure));
					return;
				}

				if ("1".equals(loginModel.getResultCode())
						&& loginModel.getData() != null && loginModel.getData().getUserVO() != null) {
					loginSuccess(loginModel);
				} else {
					mView.showLoginFrame();
				}
				mView.dismissProgress();
			}
		}, LoginModel.class, false);
	}
}
